package com.cmpe.group6.storyroad;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.Toast;

import com.cmpe.group6.storyroad.jsonClasses.ServerResponseObject;
import com.cmpe.group6.storyroad.jsonClasses.StoryObject;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.gson.Gson;

/** Activity for editing stories.
 * @author alicang, oguzaslan
 *
 */
public class EditStory extends Activity {

	private Activity currentActivity;

	private String storyId;
	private StoryObject storyObject;
	private ProgressBar progressBar;
	private ProgressBar progressBarFinish;

	private ScrollView mainScrollView;
	private String body;
	private String title;
	private String location;
	private String locationCoordinates;

	private EditText bodyView;
	private EditText titleView;
	private EditText locationDescView;

	private GoogleMap map;
	private Marker marker;
	
	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_story);
		final ActionBar bar = getActionBar();
		bar.setDisplayShowTitleEnabled(false);
		currentActivity = this;
		storyId = getIntent().getStringExtra("storyId");
		mainScrollView = (ScrollView) findViewById(R.id.edit_scrollview);
		bodyView = (EditText) findViewById(R.id.edit_story_body);
		titleView = (EditText) findViewById(R.id.edit_story_title);
		locationDescView = (EditText) findViewById(R.id.edit_location_description);
		progressBar = (ProgressBar) findViewById(R.id.progressBar_edit);
		progressBarFinish = (ProgressBar) findViewById(R.id.progressBar_edit2);
		ImageView transView = (ImageView) findViewById(R.id.edit_transparent_image);
		
		InitStoryTask initStory = new InitStoryTask();
		initStory.execute((Void) null);

		transView.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				int action = event.getAction();
				switch (action) {
				case MotionEvent.ACTION_DOWN:
					// Disallow ScrollView to intercept touch events.
					mainScrollView.requestDisallowInterceptTouchEvent(true);
					// Disable touch on transparent view
					return false;

				case MotionEvent.ACTION_UP:
					// Allow ScrollView to intercept touch events.
					mainScrollView.requestDisallowInterceptTouchEvent(false);
					return true;

				case MotionEvent.ACTION_MOVE:
					mainScrollView.requestDisallowInterceptTouchEvent(true);
					return false;

				default:
					return true;
				}
			}
		});

		map = ((MapFragment) getFragmentManager().findFragmentById(R.id.edit_map))
				.getMap();
		map.setMyLocationEnabled(true);
		map.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {

			// Adds marker if long click gesture is done on map.
			@Override
			public void onMapLongClick(LatLng arg0) {
				if (marker != null) {
					marker.remove();
				}
				marker = map.addMarker(new MarkerOptions()
						.position(new LatLng(arg0.latitude, arg0.longitude))
						.draggable(true).visible(true));
				locationCoordinates = marker.getPosition().toString();
			}
		});

		findViewById(R.id.edit_finish_story).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {

						boolean isValid = true;

						EditStoryTask editTask = new EditStoryTask();
						title = titleView.getText().toString();
						if (title.length() == 0) {
							titleView.setError("Title cannot be empty");
							titleView.requestFocus();
							isValid = false;
						}

						body = bodyView.getText().toString();
						if (body.length() == 0) {
							bodyView.setError("Story Body cannot be empty");
							bodyView.requestFocus();
							isValid = false;
						}

						location = locationDescView.getText().toString();
						if (location.length() == 0) {
							locationDescView
									.setError("Location Description cannot be empty");
							locationDescView.requestFocus();
							isValid = false;
						}

						if (marker == null) {
							Toast.makeText(getApplicationContext(),
									"Select a location using map!",
									Toast.LENGTH_SHORT).show();
							isValid = false;
						}

						if (isValid) {
							locationCoordinates = locationCoordinates.replace(
									"lat/lng: (", "");
							locationCoordinates = locationCoordinates.replace(
									")", "");
							editTask.execute((Void) null);
						}
					}
				});

	}
	
	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	/* Activating the top bar.
	 * (non-Javadoc)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.home_button:
			Intent mainIntent = new Intent(this, MainActivity.class);
			startActivity(mainIntent);
			return true;
		case R.id.recommendations_button:
			Intent recomIntent = new Intent(this, RecommendationsActivity.class);
			startActivity(recomIntent);
			return true;
		case R.id.profile_button:
			Intent profileIntent = new Intent(this, ProfileActivity.class);
			startActivity(profileIntent);
			return true;
		case R.id.search_button:
			Intent searchIntent = new Intent(this, SearchActivity.class);
			startActivity(searchIntent);
			return true;
		case R.id.following_button:
			Intent followIntent = new Intent(this, FollowingActivity.class);
			startActivity(followIntent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/**
	 * Represents an asynchronous Edit Story task to send the updated story to
	 * server.
	 * 
	 */
	public class EditStoryTask extends AsyncTask<Void, Void, Boolean> {
		
		@Override
		protected void onPreExecute(){
			progressBarFinish.setVisibility(View.VISIBLE);
		}
		
		@Override
		protected Boolean doInBackground(Void... params) {

			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(Utils.SERVER_NAME + "UpdateStory");
			ServerResponseObject responseObject = new ServerResponseObject();

			try {
				// Add your data
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				nameValuePairs.add(new BasicNameValuePair("username",
						Utils.username));
				nameValuePairs.add(new BasicNameValuePair("title", title));
				nameValuePairs.add(new BasicNameValuePair("body", body));
				nameValuePairs
						.add(new BasicNameValuePair("location", location));
				nameValuePairs.add(new BasicNameValuePair("request_type",
						"Android"));
				nameValuePairs.add(new BasicNameValuePair("coordinates",
						locationCoordinates));
				nameValuePairs.add(new BasicNameValuePair("story_id", storyId));
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,
						"UTF-8"));

				// Execute HTTP Post Request
				HttpResponse response = httpclient.execute(httppost);

				String jsonResponse = EntityUtils
						.toString(response.getEntity());
				Gson gson = new Gson();
				responseObject = gson.fromJson(jsonResponse,
						ServerResponseObject.class);

			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
			} catch (IOException e) {
				// TODO Auto-generated catch block
			}

			if (responseObject.isSuccess()) {
				return true;
			} else {
				return false;
			}
		}
		
		/*
		 * (non-Javadoc)
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(final Boolean success) {

			if (success) {
				progressBarFinish.setVisibility(View.GONE);
				Toast.makeText(getApplicationContext(),
						"Story Updated Successfully!", Toast.LENGTH_SHORT)
						.show();
				Intent mainActivityIntent = new Intent(currentActivity,
						MainActivity.class);
				startActivity(mainActivityIntent);
			} else {
				Toast.makeText(getApplicationContext(),
						"Connection error!", Toast.LENGTH_SHORT)
						.show();
			}
		}

		@Override
		protected void onCancelled() {

		}
	}

	/**
	 * Represents an asynchronous Init Story task to getting required
	 * information of the chosen story.
	 * 
	 */
	public class InitStoryTask extends AsyncTask<Void, Void, Boolean> {

		@Override
		protected void onPreExecute() {
			progressBar.setVisibility(View.VISIBLE);
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(Utils.SERVER_NAME + "ReadStory");

			try {
				// Add your data
				List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
						3);
				nameValuePairs.add(new BasicNameValuePair("request_type",
						"Android"));
				nameValuePairs.add(new BasicNameValuePair("story_id", storyId));
				nameValuePairs.add(new BasicNameValuePair("username",
						Utils.username));
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

				// Execute HTTP Post Request
				HttpResponse response = httpclient.execute(httppost);

				String jsonResponse = EntityUtils
						.toString(response.getEntity());
				Gson gson = new Gson();
				storyObject = gson.fromJson(jsonResponse, StoryObject.class);

			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
			} catch (IOException e) {
				// TODO Auto-generated catch block
			}

			return true;
		}
		
		/*
		 * (non-Javadoc)
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(final Boolean success) {

			if (!success) {
				Toast.makeText(getApplicationContext(), "Connection Error",
						Toast.LENGTH_SHORT).show();
			} else {

				titleView.setText(storyObject.getTitle());
				bodyView.setText(storyObject.getBody());
				locationDescView.setText(storyObject.getLocation());

				// Adding marker for each linked story to the map.
				marker = map.addMarker(new MarkerOptions()
						.position(
								new LatLng(storyObject.getX_coord(),
										storyObject.getY_coord()))
						.draggable(false).visible(true));
				
				LatLng coordinates = new LatLng(
						storyObject.getX_coord(),
						storyObject.getY_coord());
				
				CameraUpdate cameraUpdate = CameraUpdateFactory
						.newLatLngZoom(coordinates, 11);
				map.animateCamera(cameraUpdate);
				
				locationCoordinates = marker.getPosition().toString();

				progressBar.setVisibility(View.GONE);
			}
		}

		@Override
		protected void onCancelled() {

		}
	}

}
